package com.whfp.coky.ui.task.act

import android.app.Activity
import android.bluetooth.BluetoothGatt
import android.content.Context
import android.content.Intent
import androidx.core.content.ContextCompat
import com.clj.fastble.data.BleDevice
import com.clj.fastble.exception.BleException
import com.whfp.afs330h_sdk.bean.BLE_TestingResultBean
import com.whfp.coky.CopyFrag
import com.whfp.coky.R
import com.whfp.coky.ble.BleController
import com.whfp.coky.ble.listener.DevListener
import com.whfp.coky.ble.print.PrintBtController
import com.whfp.coky.databinding.ActivityFluorMainBinding
import com.whfp.coky.event.EventCode
import com.whfp.coky.event.EventMessage
import com.whfp.coky.ui.adpter.NavigationAdapter
import com.whfp.coky.ui.base.BaseFragment
import com.whfp.coky.ui.base.BaseNavigationActivity
import com.whfp.coky.ui.task.frag.FluorDetecFrag
import com.whfp.coky.ui.task.frag.FluorProjFrag
import com.whfp.coky.ui.task.frag.FluorSettingsFrag
import com.whfp.coky.ui.task.model.CheckDeviceBean
import com.whfp.coky.ui.task.model.FluorSettingBean
import com.whfp.coky.ui.task.vm.fluor.FluorMainVM
import com.whfp.coky.utils.AESUtils
import com.whfp.coky.utils.GsonUtils
import com.whfp.coky.widget.clicks

/**
 *
 * 荧光检测主Act
 * author coky
 * created 2022/3/16 15:34
 */
class FluorMainAct : BaseNavigationActivity<FluorMainVM, ActivityFluorMainBinding>() {

    companion object {
        @JvmOverloads
        fun start(
            context: Context,
            fragmentClass: Class<out BaseFragment<*, *>?>? = CopyFrag::class.java
        ) {
            val intent = Intent(context, FluorMainAct::class.java)
            intent.putExtra(INTENT_KEY_IN_FRAGMENT_CLASS, fragmentClass)
            if (context !is Activity) {
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            }
            context.startActivity(intent)
        }
    }

    //settingBean的get/set
    fun setSettings(settings: FluorSettingBean) {
        vModel.settingBean = settings
    }

    fun getSettings() = vModel.settingBean


    override fun initData() {
//        为vm构造蓝牙控制者
        vModel.BC = object :BleController(this, initNotifyListener(), initPirintListener()){
            override fun startConn(type: BleController.DEV_TYPE) {
//                启动连接（可能是扫码，可能是本地信息直连）
                startActivity(ScanCodeAct::class.java)
            }

            override fun connFailed(bleDev: BleDevice?, bleExc: BleException?) {
                connFailedView()
            }

            override fun connSuccess(bleDev: BleDevice?, btGatt: BluetoothGatt?, i: Int) {
                vModel.storeDev()
                connSuccessView()
            }

            override fun disConned(
                isActive: Boolean,
                bleDev: BleDevice?,
                btGatt: BluetoothGatt?,
                i: Int
            ) {
                connFailedView()
            }

        }

//      打印机连接事件
        vBinding.sbDevicePrint.getRightView().clicks {
            vModel.connPrint()
        }
//      设备连接事件
        vBinding.sbDeviceDetec.getRightView().clicks {
            vModel.connDev()
        }
    }

//----------------------------------------蓝牙回调初始化------------------------------------------
    //    设备的连接和数据交互回调..
    fun initNotifyListener() = object : DevListener(this) {


//    获取云端标曲
        override fun getCloudBq(bqName: String) {
            vModel.doGetCloudBq(bqName)
        }

    override fun onTestComplete(result: String?) {
//                上传结果
            val detecBean: BLE_TestingResultBean = GsonUtils.parseJSON(result,
                BLE_TestingResultBean::class.java)
            detecBean?.let {
                if (it.status == 1||it.status == -2){
                    toast("C线异常！")
                }else{
//                    buildFrags()
                    vModel.handleTestingResult(it)
                }
            }
        }

        override fun updateProj(json: String?) {
            vModel.updateProj(json)
        }
    }

    //  打印机的pHandler连接回调
    fun initPirintListener() = object : PrintBtController.PrintListener {
        override fun printConnSuccess(devMac:String) {
            vModel.storePrint(devMac)
            vBinding.sbDevicePrint.let {
                it.setLeftText("打印机[$devMac]已连接")
                it.setLeftTextColor(ContextCompat.getColor(getContext(), R.color.theme))
                it.setRightText("断开打印机连接")
            }
        }

        override fun printConnFailed(devMac:String) {
            vBinding.sbDevicePrint.let {
                it.setLeftText("打印机[$devMac]连接失败")
                it.setLeftTextColor(
                    ContextCompat.getColor(
                       getContext(),
                        R.color.button_selector_red
                    )
                )
                it.setRightText("扫码连接打印机")
            }
        }

        override fun printConnClosed() {
            vBinding.sbDevicePrint.let {
                it.setLeftText("打印机未连接")
                it.setLeftTextColor(
                    ContextCompat.getColor(
                        getContext(),
                        R.color.button_selector_red
                    )
                )
                it.setRightText("扫码连接打印机")
            }
        }

    }
    
    override fun handleEvent(msg: EventMessage) {
        super.handleEvent(msg)
        when (msg.code) {
//            扫码获取设备信息后进行校验
            EventCode.SCAN_CODE -> vModel.doVerDevice(msg.msg)
        }
    }

    override fun handleDevice(bean: CheckDeviceBean) {
        super.handleDevice(bean)
        //            http校验成功后,开始连接设备
        if (AESUtils.isMac(bean.deviceMac)) {
            vModel.BC?.doConn(bean)
        } else {
            toast("mac：${bean.deviceMac},不可用..")
        }
    }



    override fun onDestroy() {
        vModel.release()
        super.onDestroy()

    }
    
//    -------------------------------------view相关---------------------------------------

    //    连接成功界面展示
    fun connSuccessView() {
        vBinding.sbDeviceDetec.let {
            it.setLeftText("检测仪[${vModel.checkedDevLD.value?.refType}]已连接")
            it.setLeftTextColor(ContextCompat.getColor(getContext(), R.color.theme))
            it.setRightText("断开检测仪连接")
        }
    }


    //    连接失败和断开界面展示
    fun connFailedView() {
        vBinding.sbDeviceDetec.let {
            it.setLeftText("检测仪未连接")
            it.setLeftTextColor(
                ContextCompat.getColor(
                    getContext(),
                    R.color.button_selector_red
                )
            )
            it.setRightText("扫码连接检测仪")
        }
    }

    //基础导航界面数据配置
    override fun buildTitle() = mutableListOf(
        "臻稀检测", "项目管理", "检测记录", "系统设置"
    )

    override fun buildItems() = mutableListOf(
        NavigationAdapter.MenuItem(
            getString(R.string.main_fluor_01),
            ContextCompat.getDrawable(this@FluorMainAct, R.drawable.fluor_01_selector)
        ),
        NavigationAdapter.MenuItem(
            getString(R.string.main_fluor_02),
            ContextCompat.getDrawable(this@FluorMainAct, R.drawable.fluor_02_selector)
        ),
        NavigationAdapter.MenuItem(
            getString(R.string.main_fluor_03),
            ContextCompat.getDrawable(this@FluorMainAct, R.drawable.fluor_03_selector)
        ),
        NavigationAdapter.MenuItem(
            getString(R.string.main_fluor_04),
            ContextCompat.getDrawable(this@FluorMainAct, R.drawable.fluor_04_selector)
        )
    )

    override fun buildFrags(): MutableList<BaseFragment<*, *>> = mutableListOf(
        FluorDetecFrag.newInstance(),
        FluorProjFrag.newInstance(),
        CopyFrag.newInstance(),
        FluorSettingsFrag.newInstance(getSettings())
    )

}